package userModel

import (
	//  "fmt"
	// "errors"
	// "git.oschina.net/zd04/beego-shop/models/logModel"
	"git.oschina.net/zd04/beego-shop/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

/**
 * 定义字段和内存变量的映射关系
 */
type User struct {
	UserId  int64  `orm:"pk;column(user_id);"` //   user_id
	LoginId string `orm:"column(login_id);"`   // login_id
	Passwod string `orm:"column(passwd);"`     // passwd
	Name    string `orm:"column(name);"`       // name
	NameEn  string `orm:"column(name_en);"`    // name_en
	// DepartmentId int64  `orm:"column(department_id);"`
	// status
	// email
	// create_date
	// last_login
	// last_update
	// role_id
	//
	// position_id
	// passwd_update_date
	// telephone
	// mobile_phone
	// note
	// user_supervisor_id
	// agent_id
	// is_use_internet_ip
	// supplier_id
	// supplier_code
	// is_sync_csp
	// logon_language
	DepartmentId *Department `orm:"column(department_id);rel(one);"`
}

/*
定义对应的数据库名称
*/
func (this *User) TableName() string {
	return utils.TableName("user")
}

func init() {
	orm.RegisterModel(new(User))
}

func ListUser() (int64, []User, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(User))

	cond := orm.NewCondition()
	cond = cond.And("LoginId", "hjiang") //加了条件就要重新赋值
	qs = qs.SetCond(cond)

	var users []User
	count, err := qs.All(&users)

	return count, users, err
}

func ListUserByCond() (int64, error, []User) {
	var users []User

	qb, _ := orm.NewQueryBuilder("mysql")
	qb.Select("user.*").From("user").LeftJoin("department").On("user.department_id = department.department_id").Limit(1)

	o := orm.NewOrm()
	sql := qb.String()
	// nums, err := o.Raw(sql).Values(&users)

	nums, err := o.Raw(sql).QueryRows(&users)

	beego.Debug(users[0].DepartmentId.DepartmentId)

	UpdateUserBySql()
	return nums, err, users
}

func UpdateUserQs() {
	o := orm.NewOrm()
	//怎么设置值
	qs := o.QueryTable(new(User))
	user := make(orm.Params)
	user["department_id"] = 10
	row, err := qs.Filter("user_id", 1).Update(user)

	beego.Debug(row)
	beego.Debug(err)
}

func UpdateUserBySql() {
	o := orm.NewOrm()

	qb, _ := orm.NewQueryBuilder("mysql")

	f := []string{} //"level", "msg"
	f = append(f, "level")
	f = append(f, "msg")

	var v []string
	v = append(v, "2")
	v = append(v, orm.ToStr(`"test333"`)) //"2", `"test123"`

	qb.InsertInto("logs", f...).Values(v...)
	sql := qb.String()

	r, e := o.Raw(sql).Exec()
	beego.Debug(r, e)
}
